<template>
    <a-card :bordered="false">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
            <h2 class="text-center  margin-bottom">{{title}}</h2>
            <a-form layout="inline" @keyup.enter.native="searchQuery">
                <a-row :gutter="24">
                    <a-col :md="6" :sm="24">
                        <a-form-item label="请选择时间">
                            <a-range-picker
                                    :placeholder="['开始时间', '结束时间']"
                                    format="YYYY-MM"
                                    :value="value"
                                    :mode="mode2"
                                    @panelChange="handlePanelChange2"
                                    @change="handleChange"
                            />
                        </a-form-item>
                    </a-col>

                    <a-col :md="6" :sm="24">
                        <a-form-item label="产生单位">
                            <select-customer-list ref="selectCustomerRef" @change="changeCustomer"></select-customer-list>
                        </a-form-item>
                    </a-col>

                    <a-col :md="6" :sm="24" v-has="'query:company:select:auth'">
                        <a-form-item label="处置单位">
                            <select-company-list :companysId="queryParam.companysId" @change="changeCompany"></select-company-list>
                        </a-form-item>
                    </a-col>

                    <a-col :md="8" :sm="24" v-if="showSelectArea">
                        <a-form-item label="区域查询">
                            <select-area ref="selectAreaRef" @change="changeArea"></select-area>
                        </a-form-item>
                    </a-col>

                    <!--<a-col :sm="24">-->
                        <!--<a-form-item label="废物类型">-->
                            <!--<a-checkbox-group v-model="wasteId" :options="wasteType" @change="changeWasteType"/>-->
                        <!--</a-form-item>-->
                    <!--</a-col>-->

                </a-row>
            </a-form>
        </div>
        <!-- 查询区域-END -->

        <!-- 操作按钮区域 -->
        <div class="table-operator" style="display: flex;justify-content: space-between;align-items: center;">
            <div>
                <a-button type="primary" @click="searchQuery" icon="search">查询数据列表</a-button>
                <a-button type="primary" @click="resetForm">重置查询</a-button>
            </div>
            <div>
                <a-button type="primary" icon="printer" v-print="'#printTableList'">打印</a-button>
                <a-button style="margin-left: 10px;" @click="handleMwExportXlsForImages" type="primary" icon="download">
                    导出
                </a-button>
            </div>
        </div>

        <!-- table区域-begin -->
        <div>
            <CheckboxWasteType :companysId="queryParam.companysId" @change="changeWasteType"></CheckboxWasteType>
        </div>

        <!-- table区域-begin -->
        <div>
            <!--<div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">-->
                <!--<i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择-->
                <!--<a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项-->
                <!--<a style="margin-left: 24px" @click="onClearSelected">清空</a>-->
            <!--</div>-->
            <!--:rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"-->
            <a-table
                    ref="table"
                    size="middle"
                    bordered
                    rowKey="id"
                    :columns="columns"
                    :dataSource="dataSource"
                    :pagination="ipagination"
                    :loading="loading"

                    class="j-table-force-nowrap"
                    @change="handleTableChange"
            >
                <template slot="htmlSlot" slot-scope="text">
                    <div v-html="text"></div>
                </template>
                <template slot="imgSlot" slot-scope="text">
                    <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
                    <img v-else :src="getImgView(text)" height="25px" alt style="width: auto;height: 50px;"/>
                </template>
                <template slot="fileSlot" slot-scope="text">
                    <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
                    <a-button
                            v-else
                            :ghost="true"
                            type="primary"
                            icon="download"
                            size="small"
                            @click="uploadFile(text)"
                    >下载
                    </a-button>
                </template>
            </a-table>
        </div>

        <div v-show="false">
            <div id="printTableList">
                <h2 style="text-align: center;font-weight: bold;">
                    {{title}}
                </h2>
                <h3 v-if="rangeTime.length">时间 ： {{rangeTime[0]}} 至 {{rangeTime[1]}}</h3>
                <a-table
                        size="small"
                        bordered
                        rowKey="id"
                        :columns="columns"
                        :dataSource="dataSource"
                        :pagination="false"
                >
                    <template slot="htmlSlot" slot-scope="text">
                        <div style="color: black !important;" v-html="text"></div>
                    </template>
                    <template slot="imgSlot" slot-scope="text">
                        <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
                        <img v-else :src="getImgView(text)" height="25px" alt style="width: auto;height: 50px;"/>
                    </template>
                </a-table>
            </div>
        </div>
    </a-card>
</template>


<script>
    /**
     * create by Yang
     * 查询各区域医疗机构医废收集量月报表
     */
    import '@/assets/less/TableExpand.less'
    import { mixinDevice } from '@/utils/mixin'
    import { JeecgListMixin } from '@/mixins/JeecgListMixin'
    import SelectArea from '@/components/Jane/SelectArea'
    import SelectCompanyList from '@/components/Jane/SelectCompanyList'
    import SelectCustomerList from '@/components/Jane/SelectCustomerList'
    import CheckboxWasteType from '@/components/Jane/CheckboxWasteType'

    import waste from '@/api/waste'
    import { downloadFile } from '@/api/manage'


    export default {
        name: 'monthlyStatement',
        mixins: [JeecgListMixin, mixinDevice],
        components: {
            SelectArea,
            SelectCompanyList,
            SelectCustomerList,
            CheckboxWasteType,
        },

        data() {
            return {
                title: '医疗机构废物收集量统计月报表',
                fiveWeightAndBag: {},
                rangeTime : [],
                mode2: ['month', 'month'],
                value: [],
                queryParam: {
                    creatTimeBegin: null,
                    creatTimeEnd: null
                },
                // 表头
                columns: [],
                url: {
                    list: null, // 小董的接口 3.0
                    exportXlsUrlOkForImages: '/hc/hcRecycleRecord/exportCustomerReport',  // 小董的接口 3.0
                },
                wasteTypeList: [], // 废物类型列表 (原始数据)
                // wasteType: [], // 废物类型列表 （[{value,label}]）
                wasteId: [],  // 选择的废物
                timeList:[], // 选择的时间集合
            }
        },
        // created() {
        //     this.initData()
        // },
        mounted() {
        },
        computed: {
            showSelectArea: function() {
                let state = true
                let userInfo = this.$store.getters.userInfo
                if (userInfo.provinceCode && userInfo.cityCode && userInfo.areaCode) {
                    state = false
                }
                return state
            }
        },
        methods: {
            // 初始化数据
            async initData() {
                for (let i in this.queryParam) {
                    this.queryParam[i] = ''
                }
                // 获取到用户登陆的信息
                let userInfo = this.$store.getters.userInfo
                if (userInfo.companysId) {
                    this.queryParam.companysId = userInfo.companysId;
                }
                if (userInfo.cityCode) {
                    this.queryParam.cityCode = userInfo.cityCode
                }
                if (userInfo.areaCode) {
                    this.queryParam.areaCode = userInfo.areaCode
                }
                let ref = this.$refs.selectAreaRef
                if (ref && ref.clearSelectArea != undefined) {
                    ref.clearSelectArea()
                }
                let refCus = this.$refs.selectCustomerRef;
                if(refCus && refCus.clearSelectCustomer != undefined){
                    refCus.clearSelectCustomer();
                }
                // 获取当前时间
                let date = new Date()
                date.setMonth(date.getMonth()-2);
                var year1 = date.getFullYear();
                var month1 = date.getMonth()+1;
                month1 = (month1<10 ? '0'+month1:month1);
                // 获取当前日期的前三个月
                let sDate = (year1.toString()+'-'+month1.toString())+'-'+'01';
                let s2Date = (year1.toString()+'-'+month1.toString());
                // 默认开始时间：当前年/月/日的前3个月01日
                this.queryParam.creatTimeBegin = sDate
                // 默认打印显示的开始时间
                this.rangeTime[0] = s2Date;
                // 默认结束时间：当前年/月/日
                this.queryParam.creatTimeEnd = new Date().FormatDate()
                // 默认打印显示的结束时间
                this.rangeTime[1] = new Date().FormatMonth();
                this.mode2 = [this.queryParam.creatTimeBegin, this.queryParam.creatTimeEnd];
                this.value = [this.queryParam.creatTimeBegin, this.queryParam.creatTimeEnd];
                // await this.queryWasteList()
                this.timeList = this.getMonthBetween(this.queryParam.creatTimeBegin,this.queryParam.creatTimeEnd);


            },
            async initDictConfig() {
                this.initData()
                this.setColumns();

            },
            handleChange(value) {
                this.value = value;
            },
            // 选择日期
            handlePanelChange2(value, mode) {
                this.value = value;
                this.mode2 = [mode[0] === 'date' ? 'month' : mode[0], mode[1] === 'date' ? 'month' : mode[1]];
                // 计算月份的间隔数
                let startDate = this.value[0].format('YYYY-MM');
                let endDate = this.value[1].format('YYYY-MM');
                this.queryParam.creatTimeBegin = this.value[0].format('YYYY-MM-01');
                this.rangeTime[0] = this.value[0].format('YYYY-MM');
                this.rangeTime[1] = this.value[1].format('YYYY-MM');
                this.queryParam.creatTimeEnd = this.value[1].format('YYYY-MM-01');
                this.timeList = this.getMonthBetween(startDate,endDate);
                this.setColumns();
            },
            // 获取两个时间之间的月份
            getMonthBetween(start,end){
                //初始化数组
                var result = [];
                //切割起始年月
                var s = start.split("-");
                //切割结束年月
                var e = end.split("-");
                //获取时间对象
                var min = new Date();
                var max = new Date();
                //设置起始时间
                min.setFullYear(s[0],s[1]);
                //设置结束时间
                max.setFullYear(e[0],e[1]);
                //复制一份起始时间对象
                var curr = min;
                //定义字符串
                var str = "";
                //起始时间在结束时间之前
                while(curr <= max){
                    //获取此时间的月份
                    var month = curr.getMonth();
                    //如果月份为0，也就是代表12月份
                    if(month===0){
                        str=(curr.getFullYear()-1)+"-"+12;
                    }else{//正常月份
                        str=curr.getFullYear()+"-"+(month<10?("0"+month):month);
                    }
                    //将此年月加入数组
                    result.push(str);
                    //更新此时间月份
                    curr.setMonth(month+1);
                }
                return result;
            },

            async changeCustomer(value,option) {
                this.queryParam.customerNumber = value;
            },
            async changeCompany(value,info,option) {
                this.queryParam.companysId = value;
                this.searchQuery()
            },
            // 重置筛选表单
            resetForm() {
                this.initData()
                this.searchQuery();
            },

            // 查询废物列表
            // async queryWasteList() {
            //     let data = await waste.getWasteTypeListByCompanyId()
            //     let arr = []
            //     let wasteIds = []
            //     data.forEach((item, index) => {
            //         (item['children'] || []).forEach((val, i) => {
            //             if(index==0 ){
            //                 arr.push({
            //                     value: val.id,
            //                     label: val.wasteTypeName,
            //                     checked: true
            //                 })
            //                 wasteIds.push(val.id)
            //             }
            //             else{
            //                 arr.push({
            //                     value: val.id,
            //                     label: val.wasteTypeName,
            //                     checked: false
            //                 })
            //             }
            //         })
            //     })
            //     // 默认是选择'感染性','损伤性'
            //     this.wasteId = [wasteIds[0],wasteIds[2]]
            //     this.queryParam.wasteId = wasteIds.join(',')
            //     this.wasteTypeList = data
            //     this.wasteType = arr
            // },
            // 设置表格头部信息
            setColumns() {
                // 获取医废类型
                let data = this.wasteTypeList;
                let wasteList = [];
                // 循环出选择的废物类型
                data.forEach((item) => {
                    let child = item['children'] || [];
                    child.forEach((val) => {
                        // 如果是选中的状态，则追加在wasteList中
                        if(val.checked){
                            wasteList.push({...val});
                        }
                    })
                })

                let cols = [];
                // 循环时间列
                this.timeList.forEach((item,index)=>{
                    if(this.timeList.length){
                        let obj = {
                            title: item,
                            dataIndex: 'id',
                            key: `${index}-0`,
                            children: []
                        }
                        let newArr = [];
                        wasteList.forEach((waste, key) => {
                            let info = this.wasteId.find(v => v === waste.id);
                            if (info) {
                                newArr.push({
                                    title: waste.wasteTypeName+'(kg)',
                                    align: 'center',
                                    dataIndex: 'id',
                                    key: `${index}-${key}-0`,
                                    customRender: function(vv, row, index) {
                                        let info = [];
                                        row['data'].forEach((value,s)=>{
                                            // 判断时间是否相等
                                            if(value['monthTime'] == item){
                                                info = value['waste'].find((v) =>v.wasteId === waste.id)
                                            }
                                        })
                                        if (info) {
                                            return `${info.wastePresentValue || ' '}`
                                        }
                                        return ''
                                    }
                                });
                            }
                        })

                        // // 循环医废类型列
                        // data.forEach((waste, key) => {
                        //     (waste['children'] || []).forEach((val, i) => {
                        //         let info = this.wasteId.find(v => v === val.id)
                        //         if (info) {
                        //             newArr.push({
                        //                 title: val.wasteTypeName+'(kg)',
                        //                 align: 'center',
                        //                 dataIndex: 'id',
                        //                 key: `${index}-${i}`,
                        //                 customRender: function(vv, waste, index) {
                        //                     let info = [];
                        //                     waste['data'].forEach((value,s)=>{
                        //                         // 判断时间是否相等
                        //                         if(value['monthTime'] == item){
                        //                             info = (value['waste']).find((v) =>v.wasteId === val.id)
                        //                         }
                        //                     })
                        //                     if (info) {
                        //                         return `${info.wastePresentValue || ' '}`
                        //                     }
                        //                     return ''
                        //                 }
                        //             });
                        //         }
                        //     })
                        // })
                        obj['children'] = newArr;
                        cols.push(obj)
                    }
                });
                this.columns = [
                    {
                        title: '日期',
                        dataIndex: '',
                        key: '',
                        align: 'center',
                        children: [
                            {
                                title: '序号',
                                dataIndex: '',
                                key: 'rowIndex',
                                width: 60,
                                align: 'center',
                                customRender: function(t, r, index) {
                                    return parseInt(index) + 1
                                }
                            },
                            {
                                title: '医疗机构名称',
                                align: 'center',
                                dataIndex: 'customerName'
                            },
                        ]
                    },
                    ...cols,
                    {
                        title: '合计',
                        align: 'center',
                        dataIndex: 'id',
                        children: [
                            {
                                title: `重量（kg）`,
                                align: 'center',
                                dataIndex: 'sum',
                            }
                        ]
                    }
                ]
            },

            // 数据统计查询
            // async getStatisticData(value) {
            //     if (this.wasteId.length) {
            //         this.queryParam.wasteId = this.wasteId.join(',')
            //     }
            // },

            async changeArea({ area, city }) {
                if (city) {
                    this.queryParam.cityCode = city
                }
                if (area) {
                    this.queryParam.areaCode = area

                }
            },

            // 废物类型选择改变
             async changeWasteType(info,wasteList) {
                this.wasteId = info.ids;
                this.queryParam.wasteId = info.ids.join(',');
                this.wasteTypeList = wasteList;
                this.url.list = '/hc/hcRecycleRecord/getcustomerReport';
                this.loadData()
                this.setColumns()
            },

            searchQuery: function() {
                this.selectedRowKeys = []
                this.selectionRows = []
                this.queryParam.wasteId = this.wasteId.join(',')
                this.loadData(1)
                // this.getStatisticData()
            },

            // 导出
            handleMwExportXlsForImages() {
                if (this.wasteId.length) {
                    this.queryParam.wasteId = this.wasteId.join(',')
                    // let nameList = []
                    // this.wasteId.forEach((val) => {
                    //     let info = this.wasteType.find(item => val === item.value)
                    //     if (info) {
                    //         nameList.push(info['label'])
                    //     }
                    // })
                    // this.queryParam.wasteName = nameList.join(',')
                } else {
                    this.$message.warning('选择至少一个废物类型导出！')
                    return
                }
                let param = { ...this.queryParam }
                let name = `月报表-${new Date().FormatDate()}.xls`
                downloadFile(this.url.exportXlsUrlOkForImages, name, param)
            }
        }
    }
</script>

<style scoped>
    @import '~@assets/less/common.less';
</style>
